<template>
  <div style="width:100%;">
    <div class="query-form">
      <el-form ref="queryForm" :inline="true" :model="data_query_form">
        <el-form-item
          v-if="
            query.formData.return_type_name === '2' ||
              query.formData.return_type_name === '' ||
              query.formData.busModel === '1'
          "
          label="产品编码："
          prop="productCode"
        >
          <el-input
            v-model="data_query_form.productCode"
            type="text"
            placeholder="产品编码"
          />
        </el-form-item>
        <el-form-item
          v-if="
            query.formData.return_type_name === '2' ||
              query.formData.return_type_name === '' ||
              query.formData.busModel === '1'
          "
          label="产品名称(中)："
          prop="productName"
        >
          <el-input
            v-model="data_query_form.productName"
            type="text"
            placeholder="产品名称(中)"
          />
        </el-form-item>
        <el-form-item
          v-if="
            query.formData.return_type_name === '2' ||
              query.formData.return_type_name === '' ||
              query.formData.busModel === '1'
          "
          :label="query.searchLabel + '：'"
          prop="orginalOrderCode"
        >
          <el-input
            v-model="data_query_form.orginalOrderCode"
            type="text"
            :placeholder="query.searchLabel"
          />
        </el-form-item>

        <el-form-item
          v-if="
            query.formData.return_type_name === '1' &&
              query.formData.busModel === '2'
          "
          label="产品编码："
          prop="productCode"
        >
          <el-input
            v-model="data_query_form.factoryItemNum"
            type="text"
            placeholder="产品编码"
          />
        </el-form-item>
        <el-form-item
          v-if="
            query.formData.return_type_name === '1' &&
              query.formData.busModel === '2'
          "
          label="产品名称(中)："
          prop="productName"
        >
          <el-input
            v-model="data_query_form.itemName"
            type="text"
            placeholder="产品名称(中)"
          />
        </el-form-item>
        <el-form-item
          v-if="
            query.formData.return_type_name === '1' &&
              query.formData.busModel === '2'
          "
          label="批号："
          prop="productName"
        >
          <el-input
            v-model="data_query_form.vendorLotNumber"
            type="text"
            placeholder="批号"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="queryFormReset">重置</el-button>
          <el-button type="primary" @click="queryFormQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div
      v-if="
        query.formData.return_type_name === '2' ||
          query.formData.return_type_name === ''
      "
      class="header-info"
      style="margin-top:40px;"
    >
      <p>
        <span style="color:red;margin-left:20px;"
          >注：可退量=库存量 - 占用量</span
        >
      </p>
    </div>
    <div class="product-list">
      <el-editable
        ref="productsList"
        v-loading="productTableLoading"
        height="400"
        :need-pagination="true"
        :columns="data_product_list.columns"
        :payload="data_product_list.data"
        :static-store="store"
        @reload="reloadData"
        @select="curSelect"
        @select-all="onSelectAll"
      />
    </div>
  </div>
</template>

<script>
import ElEditable from '@components/el-editable';
import { returnProductList } from '@api/m_mall_web_v1.js';
import { queryInvOnhandItfByCustomer } from '@api/guoke_deepexi_interface_center_v1.js';
import { compact } from 'lodash';
// eslint-disable-next-line import/extensions
import {
  SALES_PRODUCTS_COLUMNS,
  ORIGINAL_SALES_PRODUCTS_COLUMNS
  // eslint-disable-next-line import/extensions
} from './product.const.js';

export default {
  name: 'ProductAddDialogProductListComponent',
  components: { ElEditable },
  props: {
    type: {
      type: String,
      default: 'default'
    },
    query: {
      type: Object,
      default() {
        return {};
      }
    },
    fetcher: {
      type: Function,
      default() {}
    },
    // eslint-disable-next-line vue/require-default-prop
    store: null
  },
  data() {
    return {
      // return_data: {
      //   factoryItemNum: '', // 产品编码
      //   itemName: '', // 产品名称
      //   vendorLotNumber: '' // 批号查询
      // },
      data_query_form: {
        productCode: '',
        productName: '',
        orginalOrderCode: '',
        factoryItemNum: '', // 产品编码
        itemName: '', // 产品名称
        vendorLotNumber: '' // 批号查询
      },
      data_product_list: {
        storageProducts: [],
        data: {},
        columns:
          this.query.formData.return_type_name === '2' ||
          this.query.formData.busModel === '1'
            ? SALES_PRODUCTS_COLUMNS
            : ORIGINAL_SALES_PRODUCTS_COLUMNS
      },
      page: 1,
      selectedProducts: [],
      productTableLoading: false
    };
  },
  created() {
    // this.queryEnterpriseType;
    this.reloadData({ number: 1, size: 20 });
  },
  methods: {
    // 根据企业id查询mdm企业类型
    // queryEnterpriseType() {
    //   this.$axios.$post(queryMdmCompanyTypeInfo).then(res => {
    //     console.log(res, '180---------');
    //   });
    // },
    reloadData(pager) {
      // 切换分页时，存储数据
      this.productTableLoading = true;
      this.page = pager.number;
      if (
        this.query.formData.return_type_name === '1' &&
        this.query.formData.busModel === '2'
      ) {
        this.fetcher({
          url: queryInvOnhandItfByCustomer,
          method: 'post',
          data: {
            page: pager.number,
            pageSize: pager.size,
            productLineCode: this.query.formData.contract_data.productLineCode,
            supplierOrgCode: this.query.formData.supplier_data.supplierCode,
            channelType: this.query.formData.contract_data.channelType,
            factoryItemNum: this.data_query_form.factoryItemNum,
            itemName: this.data_query_form.itemName,
            vendorLotNumber: this.data_query_form.vendorLotNumber,
            findItemPrice: true
          }
        })
          .then(res => {
            const result = res.data.payload ? res.data.payload : {};
            this.data_product_list.data = result;
            this.data_product_list.data.content = this.data_product_list.data.content.map(
              item => ({
                staticProductCount: Number(item.returnQuantity) || 1, // 这个字段，是用于products-list组件中，更换数量时拦截回归数据使用
                // 采购单编号+序列号+产品编码+批号+有效期+价格
                mixsIds:
                  // item.orginalOrderCode +
                  // item.seqNo +
                  item.itemNum +
                  item.vendorLotNumber +
                  item.expirationDate +
                  item.primaryUnitPrice,
                productCode: item.itemNum,
                productName: item.itemName,
                productLineName: item.productLineName,
                productUnitName: item.primaryUnitName,
                attribute1: item.specs,
                batchNo: item.vendorLotNumber,
                validDate: item.expirationDate,
                referencePrice: item.primaryUnitPrice,
                surplusStock: item.primaryTransactionQuantity, // 库存
                // occupyCount: item.                  // 占有量
                returnCount: item.availableQuantity // 可退量
              })
            );
            if (this.data_product_list.storageProducts.length > 0) {
              this.reActiveListRows();
            }
          })
          .finally(() => {
            this.productTableLoading = false;
          });
      } else {
        this.fetcher({
          url: returnProductList,
          method: 'post',
          data: {
            busModel:
              this.query.formData.contract_data.busModel ||
              this.query.formData.contract_data.businessModelCode ||
              '',
            page: pager.number,
            pageSize: pager.size,
            // 注意哦，这里的只是很骚的写法，orginalOrderCode，这个字段在新建和原单的时候，代表着不同的意义。
            // 为“发货单号”意味着是从原单进入的，否则是新建
            orginalOrderCode:
              this.query.searchLabel === '发货单号'
                ? this.query.formData.orderCodeRelate
                : this.data_query_form.orginalOrderCode,
            productName: this.data_query_form.productName,
            productCode: this.data_query_form.productCode,
            productLineCode: this.query.formData.contract_data.productLineCode,
            vendorNum: this.query.formData.supplier_data.supplierCode
          }
        })
          .then(res => {
            const result = res.data.payload ? res.data.payload : {};
            this.data_product_list.data = result;
            this.data_product_list.data.content = this.data_product_list.data.content.map(
              item => ({
                staticProductCount: Number(item.returnQuantity) || 1, // 这个字段，是用于products-list组件中，更换数量时拦截回归数据使用
                // 采购单编号+序列号+产品编码+批号+有效期+价格
                mixsIds:
                  item.orginalOrderCode +
                  item.seqNo +
                  item.productCode +
                  item.batchNo +
                  item.validDate +
                  item.referencePrice,
                ...item
              })
            );
            if (this.data_product_list.storageProducts.length > 0) {
              this.reActiveListRows();
            }
          })
          .finally(() => {
            this.productTableLoading = false;
          });
      }
    },
    reActiveListRows() {
      const curPageRow = this.data_product_list.storageProducts;
      if (curPageRow && curPageRow.length > 0) {
        curPageRow.forEach(item => {
          const findItem = this.data_product_list.data.content.find(
            it => it.mixsIds === item.mixsIds
          );
          if (findItem) {
            this.$nextTick(() => {
              this.$refs.productsList.$refs.table.toggleRowSelection(
                findItem,
                true
              );
            });
          }
        });
      }
    },
    queryFormReset() {
      // if (this.query.formData.return_type_name === '1') {
      this.data_query_form.factoryItemNum = '';
      this.data_query_form.itemName = '';
      this.data_query_form.vendorLotNumber = '';
      this.data_query_form.productCode = '';
      this.data_query_form.productName = '';
      this.data_query_form.orginalOrderCode = '';
      // } else {
      // this.$refs.queryForm.resetFields();
      // }
      this.queryFormQuery();
    },
    queryFormQuery() {
      this.reloadData({ number: 1, size: 20 });
    },
    deDuplication(curSelectedProducts) {
      this.data_product_list.storageProducts = this.data_product_list.storageProducts.concat(
        curSelectedProducts
      );
      this.data_product_list.storageProducts = this.uniqueDoubleCycle(
        this.data_product_list.storageProducts,
        'mixsIds'
      );
      return this.data_product_list.storageProducts;
    },
    onSelectAll(selection) {
      // 如果有数据，说明是全选选中状态，那么把所有的数据放入storageProducts并去重
      if (selection.length) {
        this.data_product_list.storageProducts = this.deDuplication(
          this.data_product_list.storageProducts.concat(
            this.data_product_list.data.content
          )
        );
      } else {
        // 如果没数据，就把当前页this.data_product_list.data的数据从storageProducts挨个删除
        // 即从存储的产品池中，删除当前已取消的产品（因为是全选操作，所以已取消的产品，即当页所有产品）
        this.data_product_list.storageProducts.forEach((item, index) => {
          const findItem = this.data_product_list.data.content.find(
            it => it.mixsIds === item.mixsIds
          );
          if (findItem) {
            // 猜猜这里为啥用undefined占位？
            // 因为如果删除了位置后，下标就变了，这里以下标作为标识
            this.data_product_list.storageProducts.splice(index, 1, undefined);
          }
        });
      }
      // 数组去空
      this.data_product_list.storageProducts = compact(
        this.data_product_list.storageProducts
      );
      // 因为全选的时候，我拿的是所有列表的数据，这里手动把returnCount小于等于0的数据删掉
      // 个人觉得这样的逻辑不太好，这里由于项目已经基本完善，改动很大，暂时这样处理吧
      this.data_product_list.storageProducts = this.data_product_list.storageProducts.filter(
        item => item.returnCount > 0
      );
      this.$emit('selectionChange', this.data_product_list.storageProducts);
    },
    curSelect(selection, row) {
      // 判断当前是选中还是取消,true是选中，false是取消
      let flag = null;
      flag = selection.findIndex(item => item.mixsIds === row.mixsIds) !== -1;
      // 是否存在于相应的数据中
      const storageIdx = this.data_product_list.storageProducts.findIndex(
        item => item.mixsIds === row.mixsIds
      );
      if (flag) {
        // 如果是增加，就一股脑把当前所有选中的selection都放进storageProducts，然后再去重
        this.data_product_list.storageProducts = this.deDuplication(
          this.data_product_list.storageProducts.concat(selection)
        );
      } else {
        // 如果是减少，那么直接删除在storageProducts中对应下标的数据
        this.data_product_list.storageProducts.splice(storageIdx, 1);
      }
      this.$emit('selectionChange', this.data_product_list.storageProducts);
    },
    // 去重算法
    uniqueDoubleCycle(array, key) {
      const newArr = [];
      const len = array.length;
      let isRepeat;

      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < len; i++) {
        // 第一次循环
        isRepeat = false;
        // eslint-disable-next-line no-plusplus
        for (let j = i + 1; j < len; j++) {
          // 第二次循环
          if (array[i][key] === array[j][key]) {
            isRepeat = true;
            break;
          }
        }
        if (!isRepeat) {
          newArr.push(array[i]);
        }
      }
      return newArr;
    }
  }
};
</script>

<style lang="less" scoped>
.product-list {
  display: flex;
  flex: 1;
  .pagination {
    text-align: right;
    margin-top: 20px;
  }
}
</style>
